import json
import math
import os
from flask import jsonify, render_template, request, current_app
from information.utils.encryption import encry_md5
from information.utils.response_code import RET
from . import user_blu
from .. import data,Page_MAX

@user_blu.route('/info')
def info():
    return render_template('news/user.html',data=data)

@user_blu.route('/base_info',methods=['POST'])
def base_info():
    from information import db
    from information.utils.models import User
    params_dict = request.json
    nick_name = params_dict.get('nick_name')
    signature = params_dict.get('signature')
    gender = params_dict.get('gender')
    print(gender)
    try:
        user=User.query.filter_by(id=data['user']['id']).first()
        user.nick_name=nick_name
        user.signature=signature
        user.gender=gender
        db.session.commit()
        data['user']=user.to_dict()
        print(data['user'])
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据更新失败')
    return jsonify(errno=RET.OK, errmsg='保存成功', data=data)

@user_blu.route('/pass_info',methods=['POST'])
def pass_info():
    from information.utils.models import User
    from information import db
    params_dict=request.json
    old_password = params_dict.get('old_password')
    new_password = params_dict.get('new_password')
    new_password2 = params_dict.get('new_password2')
    if not all ([old_password,new_password,new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg='输入参数不足')
    try:
        user=User.query.filter_by(id=data['user']['id']).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    if not user:
        return jsonify(errno=RET.DATAERR, errmsg='当前用户不存在')
    if user.password_hash!=encry_md5(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='当前密码不正确')
    if new_password!=new_password2:
        return jsonify(errno=RET.PARAMERR, errmsg='两次密码输入不一致')
    try:
        user.password_hash=encry_md5(new_password)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据更新失败')
    return jsonify(errno=RET.OK, errmsg='密码修改成功')

@user_blu.route('/pic_info',methods=['POST'])
def pic_info():
    from information.utils.image_storage import storage
    from information import basedir,db
    from information.utils.models import User
    avatar=request.files.get('avatar')
    #print(str(avatar))
    a=str(avatar).casefold()
    if not avatar:
        return jsonify(errno=RET.IOERR, errmsg='请选择要上传的图片')
    #判断文件格式
    if not ('.png' in a or '.jpg' in a or '.gif' in a):
        return jsonify(errno=RET.PARAMERR, errmsg='请上传正确的图片格式')
    avatar.save(basedir+'/static/news/images/avatar.png')
    with open(basedir+'/static/news/images/avatar.png', 'rb') as f:
        key=json.loads((storage(f.read()).text_body))['key']
    try:
        user=User.query.filter_by(id=data['user']['id']).first()
        user.avatar_url=key
        db.session.commit()
        data['user']=user.to_dict()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据更新失败')
    return jsonify(errno=RET.OK, errmsg='上传成功',data=data['user'])

@user_blu.route('/news_release',methods=['POST'])
def news_release():
    from information.utils.image_storage import storage
    from information.utils.models import News
    from information import basedir, db
    title=request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    #params_dict=request.json
    # title1=params_dict.get('title')
    # print(params_dict,title1)
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR, errmsg='请求参数有误')
    # 判断文件格式
    a = str(index_image).casefold()
    if not ('.png' in a or '.jpg' in a or '.gif' in a):
        return jsonify(errno=RET.PARAMERR, errmsg='请上传正确的图片格式')
    index_image.save(basedir + '/static/news/images/index_image.png')
    with open(basedir + '/static/news/images/index_image.png', 'rb') as f:
        index_image_url = 'http://pv8piohnd.bkt.clouddn.com/'+json.loads((storage(f.read()).text_body))['key']
    #print(index_image_url)
    try:
        news=News(title=title,category_id=int(category_id),digest=digest,index_image_url=index_image_url,user_id=data['user']['id'],content=content,source=data['user']['nick_name'])
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据插入失败')
    return jsonify(errno=RET.OK, errmsg='发布成功')

@user_blu.route('/news_list',methods=['GET'])
def news_list():
    from information.utils.models import User
    currentPage=int(request.args.get('p'))
    data['current_page']=currentPage
    data['news_list'] = []
    news_list = []
    try:
        news = User.query.filter_by(id=data['user']['id']).first().news_list
        for new in news:
            # data['news_list'].append(new.to_review_dict())
            news_list.append(new.to_review_dict())
        data['total_page'] = math.ceil(len(news_list) / Page_MAX)
        data['news_list'] = []
        data['news_list'] = news_list[Page_MAX * (currentPage-1):Page_MAX * currentPage]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    return render_template('news/user_news_list.html',data=data)

@user_blu.route('/collection',methods=['GET'])
def collection():
    from information.utils.models import User
    currentPage=int(request.args.get('p'))
    data['current_page']=currentPage
    data['collections'] = []
    collections_list = []
    try:
        collections = User.query.filter_by(id=data['user']['id']).first().collection_news
        for collection in collections:
            collections_list.append(collection.to_review_dict())
        data['total_page'] = math.ceil(len(collections_list) / Page_MAX)
        data['collections'] = []
        data['collections'] = collections_list[Page_MAX * (currentPage-1):Page_MAX * currentPage]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    return render_template('news/user_collection.html',data=data)

@user_blu.route('/user_follow',methods=['GET'])
def user_follow():
    from information.utils.models import User
    currentPage = int(request.args.get('p'))
    data['current_page'] = currentPage
    data['users'] = []
    follows = []
    try:
        users = User.query.filter_by(id=data['user']['id']).first().followers
        for user in users:
            follows.append(user.to_dict())
        data['total_page'] = math.ceil(len(follows) / Page_MAX)
        data['users'] = []
        data['users'] = follows[Page_MAX * (currentPage - 1):Page_MAX * currentPage]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    return render_template('news/user_follow.html', data=data)

@user_blu.route('/other_news_list',methods=['GET'])
def other_news_list():
    from information.utils.models import User
    currentPage=int(request.args.get('p'))
    user_id = request.args.get('user_id')
    #print(currentPage,user_id)
    data['current_page']=currentPage
    data['news_list'] = []
    news_list = []
    try:
        other = User.query.filter_by(id=int(user_id)).first()
        news=other.news_list
        for new in news:
            # data['news_list'].append(new.to_review_dict())
            news_list.append(new.to_review_dict())
        data['total_page'] = math.ceil(len(news_list) / Page_MAX)
        data['news_list'] = []
        data['news_list'] = news_list[Page_MAX * (currentPage-1):Page_MAX * currentPage]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据查询失败')
    return jsonify(errno=RET.OK, errmsg='请求成功',data=data)